package com.jason.common.base;

import com.jason.common.error.BusinessErrorEnum;
import com.jason.common.error.BusinessException;
import com.jason.common.vo.CommonReturnType;
import com.jason.common.vo.ErrorData;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.List;


public class BaseController {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public Object handleExException(Exception ex){
        ErrorData errorData = null;
        /*
         * 业务出错
         */
        if (ex instanceof BusinessException) {
            BusinessException businessException = (BusinessException) ex;
            errorData = new ErrorData(businessException.getErrCode(), businessException.getErrMsg());
        }
        /*
         * validate 校验出错
         */
        else if (ex instanceof BindException){
            // ex.getFieldError():随机返回一个对象属性的异常信息。如果要一次性返回所有对象属性异常信息，则调用ex.getAllErrors()
            BindException bindException = (BindException)ex;
            List<FieldError> allErrors = bindException.getFieldErrors();
            StringBuilder sb = new StringBuilder();
            allErrors.forEach(fieldError ->{
                sb.append(fieldError.getField()).append(fieldError.getDefaultMessage()).append(";");
            });
            errorData = new ErrorData(BusinessErrorEnum.PARAM_ILLEGAL_ERROR.getErrCode(), sb.toString());
        }
        /*
         * 未知错误
         */
        else {
            errorData = new ErrorData(BusinessErrorEnum.UNKNOWN_ERROR.getErrCode(), BusinessErrorEnum.UNKNOWN_ERROR.getErrMsg());
        }
        ex.printStackTrace();
        return CommonReturnType.builder("fail", errorData);
    }
}
